import 'package:flutter/material.dart';
import 'package:flutterapp/src/getX/shop/list_item_widage.dart';
import 'package:flutterapp/src/getX/shop/shop_controller.dart';
import 'package:flutterapp/src/getX/shop/shop_model.dart';
import 'package:get/get.dart';

void main() {
  runApp(RootApp());
}

class RootApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //使用 GetX第一步
    return GetMaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
      debugShowCheckedModeBanner: false,
      routes: {
        '/target': (context) => HomePage(),
      },
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  TabController _tabController;
  // 注入
  ShopController _shopController = Get.put(ShopController());

  @override
  void initState() {
    super.initState();
    _shopController.request();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder(builder: (ShopController controller) {
      // 获取数据
      List<ShopModel> classList = controller.classList;

      if (classList.length == 0) {
        return Scaffold(
          appBar: AppBar(title: Text("商品页面")),
          body: Center(
            child: Text("加载中"),
          ),
        );
      }
      _tabController = new TabController(vsync: this, length: classList.length);
      List<Tab> tabList = [];
      List<Widget> itemList = [];
      classList.forEach((element) {
        tabList.add(Tab(
          child: Text("${element.title}", style: TextStyle(fontSize: 18)),
        ));
        itemList.add(ListItemWiget(element));
      });

      return Scaffold(
        appBar: AppBar(
          title: Text("GetX 商品列表实战"),
          bottom: buildTab(tabList),
        ),
        body: buildTabView(itemList),
        floatingActionButton: buildCardCount(),
      );
    });
  }

  buildCardCount() {
    return GetBuilder(
        id: 'card',
        builder: (ShopController _controller) {
          List<int> cardList = _controller.cardList;
          return FloatingActionButton(
            child: Text("${cardList.length}"),
            onPressed: () {},
          );
        });
  }

  TabBarView buildTabView(List itemList) {
    return TabBarView(
      controller: _tabController,
      children: itemList,
    );
  }

  TabBar buildTab(List tabList) {
    return TabBar(
      controller: _tabController,
      tabs: tabList,
      isScrollable: true,
    );
  }
}
